﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Areas.Admin.Controllers
{
    public class NewsController : Controller
    {
        private readonly Manager.BLL.Admin.M_NewsBll bll = new Manager.BLL.Admin.M_NewsBll();
        //
        // GET: /Admin/News/
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.NewsSet, Ope = "view")]
        public ActionResult Index()
        {
            var query = from n in bll.GetModelList("")
                        select new Models.News
                        {
                            NewsID = n.NewsID,
                            NewsTitle = n.NewsTitle,
                            NewsContent = n.NewsContent,
                            NewsAuthor = n.NewsAuther,
                            NewsTypeName = new Manager.BLL.Admin.M_CategoryBll().GetModel(n.NewsTypeID.Value).TypeName,
                            NewsDate = n.NewsDate,
                            NewsSource=n.NewsSource,
                            IsTop=n.IsTop?"是":"否"
                        };
            return View(query.ToList<Models.News>());
        }

        [Filters.AdminAuthFilter(ModuleID=7,Ope="add")]
        public ActionResult Add()
        {
            BindSelect();
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.NewsSet, Ope = "add")]
        public ActionResult Add(Manager.Model.Admin.M_News model)
        {
            Manager.BLL.Admin.M_CategoryBll categoryBll = new Manager.BLL.Admin.M_CategoryBll();

            try
            {
                model.NewsAuther = (Session["administrator"] as Manager.Model.Admin.M_Admin).Realname;
                if (!categoryBll.Exists(model.NewsTypeID.Value))
                    ModelState.AddModelError("", Resources.Global.msg_select_exist);

                //上传
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase fileImage = Request.Files[0];
                    if (fileImage.FileName.Length != 0)
                    {
                        string urlImage = (new Manager.Tools.FileUpload()).SaveFile(fileImage, "News");
                        if (urlImage.IndexOf("/") == -1)
                        {
                            ModelState.AddModelError("NewsImage", urlImage);
                        }
                        else
                        {
                            model.NewsImage = urlImage;
                        }
                    }
                }

                if (ModelState.IsValid)
                {
                    int r = bll.Add(model);
                    if (r > 0)
                        return RedirectToAction("Index", "News");
                    else
                        ModelState.AddModelError("", Resources.Global.msg_error);
                }
            }
            catch
            {
                ModelState.AddModelError("", Resources.Global.msg_error);
            }
            BindSelect();
            return View(model);
        }

        /// <summary>
        /// 栏目类别下拉列表框
        /// </summary>
        public void BindSelect()
        {
            Manager.BLL.Admin.M_CategoryBll categoryBll = new Manager.BLL.Admin.M_CategoryBll();
            IEnumerable<SelectListItem> categorys = from c in categoryBll.GetModelList("ModuleID=" + (int)Manager.Tools.AuthPermission.ModuleTypes.NewsSet) select new SelectListItem { Value = c.TypeID.ToString(), Text = c.TypeName };
            ViewBag.CategorySelect = categorys;
        }

        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.NewsSet, Ope = "edit")]
        public ActionResult Edit(int id)
        {
            if (!bll.Exists(id))
                return RedirectToAction("Index");
            BindSelect();
            return View(bll.GetModel(id));
        }

        [HttpPost]
        [ValidateInput(false)]
        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.NewsSet, Ope = "edit")]
        public ActionResult Edit(int id, Manager.Model.Admin.M_News model)
        {
            Manager.BLL.Admin.M_CategoryBll categoryBll = new Manager.BLL.Admin.M_CategoryBll();
            model.NewsID = id;
            if(!bll.Exists(id))
                ModelState.AddModelError("", Resources.Global.msg_select_exist);
            else
                model.NewsImage = bll.GetModel(id).NewsImage;
            try
            {
                //上传
                if (Request.Files.Count > 0)
                {
                    HttpPostedFileBase fileImage = Request.Files[0];
                    if (fileImage.FileName.Length != 0)
                    {
                        bool res = (new Manager.Tools.FileUpload()).DeleteExistFile(Server.MapPath("~" + model.NewsImage));
                        string urlImage = (new Manager.Tools.FileUpload()).SaveFile(fileImage, "News");
                        if (urlImage.IndexOf("/") == -1)
                        {
                            ModelState.AddModelError("NewsImage", urlImage);
                        }
                        else
                        {
                            model.NewsImage = urlImage;
                        }
                    }
                }

                if (ModelState.IsValid)
                {
                    if (!categoryBll.Exists(model.NewsTypeID.Value))
                        ModelState.AddModelError("", Resources.Global.msg_select_exist);

                    
                    model.NewsAuther = (Session["administrator"] as Manager.Model.Admin.M_Admin).Realname;
                    bool r = bll.Update(model);
                    if (r)
                        return RedirectToAction("Index", "News");
                    else
                        ModelState.AddModelError("", Resources.Global.msg_error);
                }
            }
            catch
            {
                ModelState.AddModelError("", Resources.Global.msg_error);
            }
            BindSelect();
            return View(model);
        }

        [Filters.AdminAuthFilter(ModuleID = (int)Manager.Tools.AuthPermission.ModuleTypes.NewsSet, Ope = "del")]
        public ActionResult Del(int id)
        {
            if (!bll.Exists(id))
                return Content("<script>alert('" + Resources.Global.msg_select_exist + "');location.href='/Admin/News/Index';</script>");
            try
            {
                bool r = bll.Delete(id);
                if (r)
                    return Content("<script>alert('" + Resources.Global.msg_success + "');location.href='/Admin/News/Index';</script>");
                else
                    return Content("<script>alert('" + Resources.Global.msg_error + "');location.href='/Admin/News/Index';</script>");

            }
            catch (Exception)
            {
                return JavaScript("<script>alert('" + Resources.Global.msg_error + "');location.href='/Admin/News/Index';</script>");
            }
        }
    }
}
